var _remoteUser = null;

function RemoteUser (table_number, callbackObject) {
  
  this.callbackObject = callbackObject;
  this.ACTIVE_INTERVAL_SEC = 30;
  this.INACTIVE_INTERVAL_SEC = 8 * 60;
  this.isActive = false;
  this.intervalId = null;
  this.table_number = table_number;
  if (table_number == null) {
    this.table_number = "0";
  }
  _remoteUser = this;
  this.onActivityDetected(true);
} 


RemoteUser.prototype.onActivityDetected = function(updateNow) {
  if (updateNow) {
    this.isActive = true;
    this.updateUserStatus();
    this.isActive = false;
  }
}	

RemoteUser.prototype.scheduleNextCallback = function() {
  if (this.intervalId != null) {
	  window.clearInterval(this.intervalId);
	  this.intervalId = null;
  }
  if (this.intervalId == null) {
    var intervalMSec = (this.isActive)? this.ACTIVE_INTERVAL_SEC * 1000 : this.INACTIVE_INTERVAL_SEC * 1000;
    this.intervalId = window.setInterval("_remoteUser.updateUserStatus()", intervalMSec);
  }    
}

RemoteUser.prototype.updateUserStatus = function() {
    var url = "/updateUserStatus";
    url += "?table=" + this.table_number + "&is_active=" + this.isActive;
    downloadUrl(url, "GET", null, onUpdateUserStatus);
    this.isActive = false;
    this.scheduleNextCallback();
}    

// static
onUpdateUserStatus = function(response) {
   response = parseResponse(response);
   if (response.users == null || response.users.length == 0) {
     if (this.intervalId != null) {
       window.clearInterval(this.intervalId);
       this.intervalId = null;
     }
   } else {  
     _remoteUser.callbackObject.updateUsers(response.users);
   }
}
